﻿using Dapper;
using System;
using BCEntity.TMS.OrderFreightRecord;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.TMS.OrderFreightRecord
{
    /// <summary>
    /// 订单运费
    /// </summary>
    public class OrderFreightRecordData : IOrderFreightRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM orderfreightrecord";
        private const string QUERY = @"SELECT OrderFreightRecordId,CostCode,CostTitle,CostValue,OrderId,OrderNo,ParentCostCode,IsOrderNewFreight,CreateTime FROM orderfreightrecord";
        public OrderFreightRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查订单运费是否存在
        public async Task<bool> Exists(long orderFreightRecordId)
        {
            string sql = string.Format(@"{0} WHERE OrderFreightRecordId=?OrderFreightRecordId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?OrderFreightRecordId", orderFreightRecordId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加订单运费
        public async Task<bool> Add(List<OrderFreightRecordEntity> entities)
        {
            return await this.databaseContext.Master.InsertAllAsync(entities, databaseContext.Transaction) > 0;
        }
        public async Task<OrderFreightRecordEntity> Add(OrderFreightRecordEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("orderfreightrecord", new string[] { "CostCode", "CostTitle", "CostValue", "OrderId", "OrderNo", "IsOrderNewFreight", "ParentCostCode" });
            sql = string.Format("{0} {1} WHERE OrderFreightRecordId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CostCode", entity.CostCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CostTitle", entity.CostTitle?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CostValue", entity.CostValue, DbType.Decimal, size: 10);
            parameters.Add("?OrderId", entity.OrderId, DbType.Int64, size: 20);
            parameters.Add("?OrderNo", entity.OrderNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ParentCostCode", entity.ParentCostCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?IsOrderNewFreight", entity.IsOrderNewFreight, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<OrderFreightRecordEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改订单运费
        public async Task<OrderFreightRecordEntity> Update(OrderFreightRecordEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("orderfreightrecord", new string[] { "CostCode", "CostTitle", "CostValue", "OrderId", "OrderNo", "ParentCostCode", "IsOrderNewFreight" }, new string[] { "OrderFreightRecordId" });
            sql = string.Format("{0} {1} WHERE OrderFreightRecordId=?OrderFreightRecordId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?OrderFreightRecordId", entity.OrderFreightRecordId, DbType.Int64, size: 20);
            parameters.Add("?CostCode", entity.CostCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CostTitle", entity.CostTitle?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CostValue", entity.CostValue, DbType.Decimal, size: 10);
            parameters.Add("?OrderId", entity.OrderId, DbType.Int64, size: 20);
            parameters.Add("?OrderNo", entity.OrderNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ParentCostCode", entity.ParentCostCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?IsOrderNewFreight", entity.IsOrderNewFreight, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<OrderFreightRecordEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除订单运费
        public async Task<bool> Delete(long orderFreightRecordId)
        {
            string sql = @"DELETE FROM orderfreightrecord WHERE OrderFreightRecordId=?OrderFreightRecordId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?OrderFreightRecordId", orderFreightRecordId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取订单运费
        public async Task<OrderFreightRecordEntity> GetEntity(long orderFreightRecordId)
        {
            string sql = string.Format(@"{0} WHERE OrderFreightRecordId=?OrderFreightRecordId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?OrderFreightRecordId", orderFreightRecordId, DbType.Int64);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<OrderFreightRecordEntity>(sql, parameters);
        }
        #endregion

        #region 获取订单运费列表
        public async Task<IEnumerable<OrderFreightRecordEntity>> GetList(string orderNo)
        {
            string sql = string.Format("{0} WHERE OrderNo=?OrderNo AND IsOrderNewFreight=1", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("OrderNo", orderNo, DbType.AnsiString);
            return await this.databaseContext.Master.QueryAsync<OrderFreightRecordEntity>(sql, parameters);
        }
        public async Task<IEnumerable<OrderFreightRecordEntity>> GetList(long orderId)
        {
            string sql = string.Format("{0} WHERE OrderId=?OrderId AND IsOrderNewFreight=1", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("OrderId", orderId, DbType.Int64);
            return await this.databaseContext.Master.QueryAsync<OrderFreightRecordEntity>(sql, parameters);
        }
        #endregion

        #region 获取订单运费分页
        public async Task<(IEnumerable<OrderFreightRecordEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM orderfreightrecord {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.QueryMultipleAsync<OrderFreightRecordEntity, int>(sql, parameters);
        }
        #endregion
    }
}



